package com.course.service;

import com.course.entity.User;
import com.course.util.DatabaseUtil;

import java.util.List;
import java.util.stream.Collectors;

public class UserService {
    private static final String USER_FILE = "users.dat";

    // 用户登录
    public User login(String username, String password) {
        List<User> users = DatabaseUtil.loadFromFile(USER_FILE);
        return users.stream()
                .filter(user -> user.getUsername().equals(username) && 
                        user.getPassword().equals(password))
                .findFirst()
                .orElse(null);
    }

    // 添加用户
    public boolean addUser(User user) {
        List<User> users = DatabaseUtil.loadFromFile(USER_FILE);
        // 检查用户名是否已存在
        if (users.stream().anyMatch(u -> u.getUsername().equals(user.getUsername()))) {
            return false;
        }
        user.setId(DatabaseUtil.generateId(USER_FILE));
        users.add(user);
        DatabaseUtil.saveToFile(USER_FILE, users);
        return true;
    }

    // 更新用户信息
    public boolean updateUser(User user) {
        List<User> users = DatabaseUtil.loadFromFile(USER_FILE);
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).getId() == user.getId()) {
                users.set(i, user);
                DatabaseUtil.saveToFile(USER_FILE, users);
                return true;
            }
        }
        return false;
    }

    // 删除用户
    public boolean deleteUser(int userId) {
        List<User> users = DatabaseUtil.loadFromFile(USER_FILE);
        boolean removed = users.removeIf(user -> user.getId() == userId);
        if (removed) {
            DatabaseUtil.saveToFile(USER_FILE, users);
        }
        return removed;
    }

    // 获取所有用户
    public List<User> getAllUsers() {
        return DatabaseUtil.loadFromFile(USER_FILE);
    }

    // 根据角色获取用户
    public List<User> getUsersByRole(String role) {
        List<User> users = DatabaseUtil.loadFromFile(USER_FILE);
        return users.stream()
                .filter(user -> user.getRole().equals(role))
                .collect(Collectors.toList());
    }

    // 根据ID获取用户
    public User getUserById(int userId) {
        List<User> users = DatabaseUtil.loadFromFile(USER_FILE);
        return users.stream()
                .filter(user -> user.getId() == userId)
                .findFirst()
                .orElse(null);
    }
} 